package generator

import (
	"flag"
	"fmt"
	"google.golang.org/protobuf/compiler/protogen"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/pluginpb"
	"io/ioutil"
	"os"
)

var s = flag.String("a", "", "a")

func Gen() {
	flag.Parse()
	fmt.Fprintf(os.Stderr, "start:%s\n", *s)
	//生成Request
	input, _ := ioutil.ReadAll(os.Stdin)
	var req pluginpb.CodeGeneratorRequest
	proto.Unmarshal(input, &req)

	//设置参数,生成plugin
	opts := protogen.Options{
		ParamFunc: flag.CommandLine.Set,
	}
	plugin, err := opts.New(&req)
	if err != nil {
		panic(err)
	}

	fmt.Fprintf(os.Stderr, "a=%s\n", *s)

	// protoc 将一组文件结构传递给程序处理,包含proto中import中的文件
	for _, file := range plugin.Files {
		if !file.Generate { //显示传入的文件为true
			continue
		}
		if len(file.Enums) != 1 { //本例子只支持一个错误枚举类型
			continue
		}
		fmt.Fprintf(os.Stderr, "path:%s\n", file.GoImportPath)
		genF := plugin.NewGeneratedFile(fmt.Sprintf("%s_error.pb.go", file.GeneratedFilenamePrefix), file.GoImportPath)
		GenFile(genF, file, *s)
	}


	// 生成response
	resp := plugin.Response()
	out, err := proto.Marshal(resp)
	if err != nil {
		panic(err)
	}

	// 相应输出到stdout, 它将被 protoc 接收
	fmt.Fprintf(os.Stdout, string(out))
}
